<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目地址" prop="area">
        <el-cascader
          placeholder="请选择项目地址"
          :options="localAddress"
          v-model="queryParams.area"
          clearable
          @keyup.enter.native="handleQuery"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入项目详细地址"
          v-show="isTable"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:project:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:project:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:project:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          v-show="isTable"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:project:export']"
          >导出</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          type="info"
          size="mini"
          @click="isTable = !isTable"
          >切换展示方式</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div v-show="!isTable" class="map-container">
      <baidu-map
        class="map-container"
        :ak="ak"
        :center="center"
        :scroll-wheel-zoom="true"
        :zoom="zoom"
        :enableDragging="enableDragging"
        @ready="handler"
      >
        <bm-marker
          v-for="(item, index) in markers"
          :key="index"
          :position="item.point"
          :icon="{ url: item.icon, size: { width: 64, height: 64 } }"
          :title="item.title"
          :zIndex="99999999999999"
        ></bm-marker>
      </baidu-map>
    </div>

    <el-table
      v-show="isTable"
      v-loading="loading"
      :data="projectList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="项目名称"
        :show-overflow-tooltip="true"
        align="center"
        prop="name"
      />
      <el-table-column
        label="省(直辖市)"
        :show-overflow-tooltip="true"
        align="center"
        prop="province"
      />
      <el-table-column
        label="市"
        :show-overflow-tooltip="true"
        align="center"
        prop="city"
      />
      <el-table-column
        label="区"
        :show-overflow-tooltip="true"
        align="center"
        prop="country"
      />
      <el-table-column
        label="详细地址"
        :show-overflow-tooltip="true"
        align="center"
        prop="address"
      />
      <el-table-column
        label="设备编号"
        :show-overflow-tooltip="true"
        align="center"
        prop="deviceId"
      />
      <el-table-column
        v-show="isTable"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:project:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:project:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="isTable"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>

        <el-form-item label="项目描述" prop="details">
          <el-input v-model="form.details" placeholder="请输入项目描述" />
        </el-form-item>
        <el-form-item label="项目地址" prop="area">
          <el-cascader
            placeholder="请选择项目地址"
            :options="localAddress"
            v-model="form.area"
          />
        </el-form-item>

        <el-form-item label="成立日期" prop="createTime">
          <el-date-picker
            clearable
            v-model="form.createTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择成立日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="项目图片">
          <el-upload
            multiple
            :limit="10"
            accept=".jpg, .png"
            :action="upload.url"
            :headers="upload.headers"
            list-type="picture-card"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-remove="handleRemove"
            :on-preview="handlePictureCardPreview"
            :class="{ hide: this.upload.fileList.length >= 10 }"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  addressLongitude,
} from "@/api/project/project";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
import { getToken } from "@/utils/auth";
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
//地图视图
import BmView from "vue-baidu-map/components/map/MapView";

import BmLocalSearch from "vue-baidu-map/components/search/LocalSearch"; //搜索
//点标注
import BmMarker from "vue-baidu-map/components/overlays/Marker";
//标注弹窗
import BmInfoWindow from "vue-baidu-map/components/overlays/InfoWindow";
import img from "@/assets/icons/定位.png";
export default {
  name: "Project",
  components: {
    BaiduMap,
    BmView,
    BmLocalSearch,
    BmMarker,
    BmInfoWindow,
  },
  data() {
    return {
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      longitudeParams: {
        address: null,
        ak: null,
        output: null,
      },
      localAddress: regionData,
      //false为地图显示，true为表格显示
      isTable: false,
      ak: "NQcvN164flbdWc7LfiB8zqbdWpBgpwcG",
      center: { lng: 110.404449, lat: 29.914889 },
      zoom: 5,
      enableDragging: true,
      // 存放marker数据的数组
      markers: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        country: null,
        city: null,
        province: null,
        address: null,
        latitude: null,
        deviceId: null,
        area: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        address: [{ required: true, message: "项目地址不能为空", trigger: "blur" }],
        deviceId: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      this.loading = true;
      this.form.imageList = [];
      for (let i = 0; i < fileList.length; i++) {
        let img = {
          imageAddress: fileList[i].url,
          projectId: this.form.id,
        };

        this.form.imageList.push(img);
      }
      this.loading = false;
    },
    handlePreview(file, fileList) {
      // console.log(file);
    },
    handleDownload(file) {
      // console.log(file);
    },

    handleChange(value) {
      // console.log(value);
    },
    queryLongitude() {
      this.longitudeParams.address = this.form.address;
      this.longitudeParams.ak = this.ak;
      // this.output.address=this.form.address
      addressLongitude(this.longitudeParams);
    },
    handler({ BMap, map }) {
      // console.log(BMap);
    },
    // 处理地图点击事件
    handleMapClick(event) {
      const point = event.point;
      this.addMarker(point);
    },
    // 添加marker
    // addMarker(point) {
    //   const marker = {
    //     point: { lng: 116.404449, lat: 39.914889 },
    //     icon: img,
    //     title: "位置1",
    //     label: "位置1",
    //   };
    //   // 将marker添加到markers数组中
    //   this.markers.push(marker);
    //   // 更新地图显示
    //   //   this.$refs.baiduMap.zoomTo(this.markers);
    // },
    // 根据后端传递的经纬度数据初始化地图
    initMap() {
      for (let i = 0; i < this.projectList.length; i++) {
        let temp = this.projectList[i].latitude.split(",");

        let marker = {
          point: { lng: temp[0], lat: temp[1] },
          icon: img,
          title: this.projectList[i].name,
          label: this.projectList[i].address,
        };
        // 添加一个初始marker
        this.markers.push(marker);
      }
    },

    /** 查询项目信息列表 */
    getList() {
      this.loading = true;
      // let a = CodeToText(this.queryParams.area);
      if (this.queryParams.area != undefined) {
        this.queryParams.province = CodeToText[this.queryParams.area[0]];
        this.queryParams.city = CodeToText[this.queryParams.area[1]];
        this.queryParams.country = CodeToText[this.queryParams.area[2]];
        console.log(this.queryParams.area);
      }

      listProject(this.queryParams).then((response) => {
        this.projectList = response.rows;
        console.log(this.projectList);
        if (!this.isTable) {
          this.markers = [];
          this.initMap();
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.form.imageList = [];
      this.upload.fileList = [];
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        country: null,
        city: null,
        province: null,
        address: null,
        latitude: null,
        details: null,
        deviceId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        version: null,
        area: null,
        imageList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryForm = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.upload.fileList = [];
      this.reset();
      this.open = true;
      this.title = "添加项目信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.upload.fileList = [];
      this.reset();
      const id = row.id || this.ids;
      getProject(id).then((response) => {
        this.form = response.data;
        this.form.area = [];
        for (let i = 0; i < this.form.imageList.length; i++) {
          let file = {
            name: this.form.imageList[i].id,
            url: this.form.imageList[i].imageAddress,
          };
          this.upload.fileList.push(file);
        }
        let province = TextToCode[this.form.province];
        let city = province[this.form.city];
        let country = city[this.form.country];
        this.form.area.push(province.code);
        this.form.area.push(city.code);
        this.form.area.push(country.code);
        this.open = true;
        this.title = "修改项目信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            console.log(this.upload.fileList);
            updateProject(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.province = CodeToText[this.form.area[0]];
            this.form.city = CodeToText[this.form.area[1]];
            this.form.country = CodeToText[this.form.area[2]];
            console.log(this.queryParams.area);
            addProject(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除项目信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delProject(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "project/project/export",
        {
          ...this.queryParams,
        },
        `project_${new Date().getTime()}.xlsx`
      );
    },
    // 文件提交处理
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.filePath = response.url;
      let image = {
        imageAddress: this.form.filePath,
        projectId: this.form.id,
      };
      this.form.imageList.push(image);
      this.$message({
        message: "上传成功",
        type: "success",
      });
      // this.msgSuccess(response.msg);
    },
  },
};
</script>
<style scoped>
.map-container {
  width: 1300px;
  height: 500px;
}
</style>
